#include "dataobject.h"

#include <istream>
#include <stdexcept>
#include <stdint.h>

#include <QString>

#include "chunkreader.h"
#include "utils.h"

template<>
std::istream & operator>>(std::istream & stream, DataObject<QString> & object)
{
    ChunkReader reader(stream, "mhod");
    uint32_t type;
    reader.read(type);
    object.type = DataObjectType::Type(type);
    reader.ignore_rest_of_header();

    DEFINE_AND_READ(encoding, uint32_t, stream);
    DEFINE_AND_READ(data_length, uint32_t, stream);
    DEFINE_AND_READ(unknown_3, uint32_t, stream);
    DEFINE_AND_READ(unknown_4, uint32_t, stream);

    char* native_buffer = new char[data_length];
    stream.read(native_buffer, data_length);
    if(encoding != 0x02)
    {
        // UTF-16 string, convert to UTF-8
        object.value = QString::fromUtf16(
            reinterpret_cast<ushort*>(native_buffer), data_length/2);
    }
    else
    {
        // UTF-8 string
        object.value = QString::fromUtf8(native_buffer, data_length);
    }

    return stream;
}
